package com.acme.exchange.network.client;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

import com.acme.exchange.gui.userDataEnter;
import com.acme.exchange.network.MessageTransceiver;
import com.acme.exchange.network.proto.Protocol.ExchangeMessage;

public class ClientOrderWriter implements Runnable {
	private ExchangeMessage newOrder;
	private MessageTransceiver mt;
	private SelectionKey key;

	public ClientOrderWriter(SelectionKey key) {
		this.key = key;
		mt = new MessageTransceiver();
	}

	@Override
	public void run() {
		userDataEnter ude = new userDataEnter();
		try {
			newOrder = ude.loginEntering();					
			synchronized ((SocketChannel)key.channel()) {
				mt.transmit(newOrder.toByteArray(), (SocketChannel)key.channel());
			}

			do {
				newOrder = ude.orderEntering();
				synchronized ((SocketChannel)key.channel()) {					
					mt.transmit(newOrder.toByteArray(), (SocketChannel)key.channel());					
					key.channel().wait(10000);
				}
			} while (!ude.getUserCommand().equals("exit"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
